package com.lidx.back.statistics.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.AesCipherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.lidx.back.statistics.commons.Constants;
import com.lidx.back.statistics.entity.ClientInfo;
import com.lidx.back.statistics.entity.FeedBack;
import com.lidx.back.statistics.entity.Filter;
import com.lidx.back.statistics.entity.MaterialCount;
import com.lidx.back.statistics.entity.UserActionMsg;
import com.lidx.back.statistics.service.IClientService;
import com.lidx.back.statistics.service.IDataService;
import com.lidx.back.statistics.service.IFilterService;
import com.lidx.back.statistics.service.IMaterialCountService;
import com.lidx.back.statistics.service.IPicShareService;
import com.lidx.back.statistics.utils.ExcelUtil;

@Controller
public class FrontUserController {
	
	private static final Logger logger = LogManager.getLogger(FrontUserController.class);
	
	@Autowired
	private IDataService dataService;
	@Autowired
	private IMaterialCountService mCountService;
	@Autowired
	private IFilterService filterService;
	@Autowired
	private IClientService clientService;
	@Autowired
	private IPicShareService picShareService;
	
	@RequestMapping(value={"/index.html","/index","/",""},method=RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView maView = new ModelAndView("index");
		return maView;
	}

	/*@RequestMapping(value="/queryData",method=RequestMethod.POST)
	public ModelAndView queryData(@RequestParam(value="type") String type,
			@RequestParam(value="versionType",required=false) String versionType){
		logger.info(type);
		ModelAndView mav = new ModelAndView("index");
		
		if(StringUtils.isEmpty(versionType)){
			return mav;
		}
		mav.addObject("versionType", versionType);
		if(!StringUtils.isEmpty(type)){
			mav.addObject("type", type);
			if(Constants.QUERY_MATERIAL_DATA.equals(type)){
				List<MaterialCount> materialCounts = mCountService.getCounts(versionType);
				if(null != materialCounts){
					mav.addObject("materialCounts", materialCounts);
				}
			}else if(Constants.QUERY_FILTER_DATA.equals(type)){
				List<Filter> filters = filterService.getFilters(versionType);
				if(null != filters){
					mav.addObject("filters", filters);
				}
			}else if(Constants.QUERY_CLIENT_DATA.equals(type)){
				List<ClientInfo> infos = clientService.getClientInfos(versionType);
				if(null != infos){
					UserActionMsg userActionMsg = clientService.dealClientInfos(infos);
					mav.addObject("userActionMsg", userActionMsg);
				}
			}else if(Constants.QUERY_PICTURE_SHARE_DATA.equals(type)){
				Map<String, Integer> map = picShareService.getSharePicChannel(versionType);
				if(null != map){
					mav.addObject("picShareData", map);
				}
			}
		}
		
		return mav;
	}
	@RequestMapping(value="exportExcel",method=RequestMethod.POST)
	public String exportExcel(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value="type") String type,
			@RequestParam(value="versionType",required=false) String versionType) throws IOException{
		String fileName ="";
        //填充FeedBacks数据
		String columnNames[] = null;
		String keys[] = null;
		List<Map<String,Object>> list = Lists.newArrayList();
		if(!StringUtils.isEmpty(type)){
			if(Constants.QUERY_MATERIAL_DATA.equals(type)){
				List<MaterialCount> materialCounts = mCountService.getCounts(versionType);
				fileName = "素材相关统计数据";
				list=createExcelMaterialRecord(materialCounts);
				columnNames= new String[]{"素材uuid","素材下载量","素材制作视频数量","素材拍照数量","素材图片的分享量","素材的视频的分享量"};//列名
		        keys  =  new String[] {"uuid","downloadNum","makeVideoNum","photographNum","picShareNum","videoShareNum"};//map中的key
			}else if(Constants.QUERY_FILTER_DATA.equals(type)){
				List<Filter> filters = filterService.getFilters(versionType);
				fileName = "滤镜相关统计数据";
				list=createExcelFilterRecord(filters);
				columnNames= new String[]{"滤镜名字","通用滤镜的使用量","通用滤镜的制作量"};//列名
		        keys  =  new String[] {"filterName","useNum","makeNum"};//map中的key
			}else if(Constants.QUERY_CLIENT_DATA.equals(type)){
				List<ClientInfo> infos = clientService.getClientInfos(versionType);
				if(null != infos){
					UserActionMsg userActionMsg = clientService.dealClientInfos(infos);
					fileName = "用户行为相关统计数据";
					list=createExcelUserActionRecord(userActionMsg);
					columnNames= new String[]{"男性数量","女性数量","用户关闭声音的次数","用户开启闪光灯的次数","用户切换摄像头的次数",
							"用户使用滤镜快速切换的次数","用户录制视频的平均时长","用户分享推荐链接数统计","用户保存视频到本地的次数",
							"用户保存照片到本地的次数","用户分享视频数统计"};//列名
			        keys  =  new String[] {"maleNum","femaleNum","closeSoundNum","openFlashLightNum",
			        		"switchCameraNum","switchFilterNum","avgRecordVideoTime","linkShareNum",
			        		"saveVideoNum","savePictureNum","shareVideoNum"};//map中的key
				}
			}else if(Constants.QUERY_PICTURE_SHARE_DATA.equals(type)){
				Map<String, Integer> map = picShareService.getSharePicChannel(versionType);
				fileName = "分享渠道相关统计数据";
		        Workbook wb = new HSSFWorkbook();
		        Sheet sheet = wb.createSheet("sheet1");
		        Row row = sheet.createRow((short) 0);
		        for(int i=0;i<2;i++){
		            sheet.setColumnWidth((short) i, (short) (35.7 * 150));
		            if(i==0){
		            	Cell cell = row.createCell(i);
	            	    cell.setCellValue("分享渠道");
		            }else{
		            	Cell cell = row.createCell(i);
	            	    cell.setCellValue("分享次数");
		            }
		        }
		        short i = 1;
		        for (String key : map.keySet()) {
		            Row row1 = sheet.createRow((short) i);
		            // 在row行上创建一个方格
		            Cell cell = row1.createCell(0);
		            cell.setCellValue(key);
		            cell = row1.createCell(1);
		            cell.setCellValue(map.get(key));
		            i++;
		        }
		        ByteArrayOutputStream os = new ByteArrayOutputStream();
		        wb.write(os);
		        responseSet(response, os, fileName);
			}
		}
        //List<FeedBack> FeedBacks= dataService.getBacks();
        //List<Map<String,Object>> list=createExcelRecord(FeedBacks);
        //String columnNames[]={"ID","设备名字","设备id","设备操作系统"};//列名
        //String keys[]    =     {"id","devicename","deviceid","deviceos"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list,keys,columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        return null;
		
	}*/
	
	private List<Map<String, Object>> createExcelUserActionRecord(
			UserActionMsg msg) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sheetName", "sheet1");
        listmap.add(map);
        Map<String, Object> mapValue = new HashMap<String, Object>();
        mapValue.put("maleNum", msg.getMaleNum());
        mapValue.put("femaleNum", msg.getFemaleNum());
        mapValue.put("closeSoundNum", msg.getCloseSoundNum());
        mapValue.put("openFlashLightNum", msg.getOpenFlashLightNum());
        mapValue.put("switchCameraNum", msg.getSwitchCameraNum());
        mapValue.put("switchFilterNum", msg.getSwitchFilterNum());
        mapValue.put("avgRecordVideoTime", msg.getAvgRecordVideoTime());
        mapValue.put("linkShareNum", msg.getLinkShareNum());
        mapValue.put("saveVideoNum", msg.getSaveVideoNum());
        mapValue.put("savePictureNum", msg.getSavePictureNum());
        mapValue.put("shareVideoNum", msg.getShareVideoNum());
        listmap.add(mapValue);
        return listmap;
	}
	
	 private List<Map<String, Object>> createExcelMaterialRecord(
			List<MaterialCount> materialCounts) {
		 List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
	        Map<String, Object> map = new HashMap<String, Object>();
	        map.put("sheetName", "sheet1");
	        listmap.add(map);
	        MaterialCount materialCount=null;
	        for (int j = 0; j < materialCounts.size(); j++) {
	        	materialCount=materialCounts.get(j);
	            Map<String, Object> mapValue = new HashMap<String, Object>();
	            mapValue.put("uuid", materialCount.getUuid());
	            mapValue.put("downloadNum", materialCount.getDownloadNum());
	            mapValue.put("makeVideoNum", materialCount.getMakeVideoNum());
	            mapValue.put("photographNum", materialCount.getPhotographNum());
	            mapValue.put("picShareNum", materialCount.getPicShareNum());
	            mapValue.put("videoShareNum", materialCount.getVideoShareNum());
	            listmap.add(mapValue);
	        }
	        return listmap;
	}
	 

	private List<Map<String, Object>> createExcelPicShareRecord(Map<String, Integer> mapPic) {
	        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
	        Map<String, Object> map = new HashMap<String, Object>();
	        map.put("sheetName", "sheet1");
	        listmap.add(map);
	        
	        //FeedBack feedBack=null;
	        /*for (int j = 0; j < FeedBacks.size(); j++) {
	            feedBack=FeedBacks.get(j);
	            Map<String, Object> mapValue = new HashMap<String, Object>();
	            mapValue.put("id", feedBack.getId());
	            mapValue.put("devicename", feedBack.getDeviceName());
	            mapValue.put("deviceid", feedBack.getDeviceId());
	            mapValue.put("deviceos", feedBack.getDeviceOS());
	            listmap.add(mapValue);
	        }*/
	      //遍历map中的键  
	        Map<String, Object> mapValue = null;
	        for (String key : mapPic.keySet()) {  
	          
	            mapValue = new HashMap<String, Object>();
	            mapValue.put(key, mapPic.get(key));
	          
	        } 
	        listmap.add(mapValue);
	        return listmap;
    }
	
	private String responseSet(HttpServletResponse response,ByteArrayOutputStream os,String fileName){
		try{
		byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content); 
		response.reset();
	        response.setContentType("application/vnd.ms-excel;charset=utf-8");
	        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
	        ServletOutputStream out = response.getOutputStream();
	        BufferedInputStream bis = null;
	        BufferedOutputStream bos = null;
	        try {
	            bis = new BufferedInputStream(is);
	            bos = new BufferedOutputStream(out);
	            byte[] buff = new byte[2048];
	            int bytesRead;
	            // Simple read/write loop.
	            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
	                bos.write(buff, 0, bytesRead);
	            }
	        } catch (final IOException e) {
	            throw e;
	        } finally {
	            if (bis != null)
	                bis.close();
	            if (bos != null)
	                bos.close();
	        }
		}catch(Exception e){
			e.printStackTrace();
		}
	        return null;
	}
	
}
